package com.javastudy.autowiredStudy.asyncStudy;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * spring项目中使用的线程池
 * @author mac
 * @date 2021/9/8 10:07 上午
 */
@Configuration
public class SpringThreadPoolConf {
    /**
     * 核心线程数
     */
    @Value("${thread.pool.corePoolSize:5}")
    private int corePoolSize;

    /**
     * 最大线程数
     */
    @Value("${thrad.pool.maxPoolSize:10}")
    private int maxPoolSize;

    /**
     * 阻塞队列的容量
     */
    @Value("${thrad.pool.queueCapacity:200}")
    private int queueCapacity;
    /**
     * 存活时间
     */
    @Value("${thrad.pool.keepAliveSeconds:30}")
    private int keepAliveSeconds;

    /**
     * 线程名称前缀
     */
    @Value("${thrad.pool.threadNamePrefix:ASYNC_}")
    private String threadNamePrefix;

    @Bean
    public Executor getExecutor(){
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(corePoolSize);
        threadPoolTaskExecutor.setMaxPoolSize(maxPoolSize);
        threadPoolTaskExecutor.setQueueCapacity(queueCapacity);
        threadPoolTaskExecutor.setKeepAliveSeconds(keepAliveSeconds);
        threadPoolTaskExecutor.setThreadNamePrefix(threadNamePrefix);
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        threadPoolTaskExecutor.initialize();

        return threadPoolTaskExecutor;
    }
}
